package com.dinghui.ebookbag.module.middle;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.dinghui.ebookbag.BaseActivity;
import com.dinghui.ebookbag.R;
import com.dinghui.ebookbag.enity.Msg;
import com.dinghui.ebookbag.enity.PackInfo;
import com.dinghui.ebookbag.enity.User;
import com.dinghui.ebookbag.module.middle.adapter.MsgAdapter;
import com.dinghui.ebookbag.module.middle.adapter.OnlineStuAdapter;
import com.dinghui.ebookbag.utils.Util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FlipClassroomActivity extends AppCompatActivity implements View.OnClickListener {

    // 定义本程序通信所使用的字符集
    public static final String CHARSET = "utf-8";
    //定义本程序的MulticastSocket实例
    private MulticastSocket socket = null;
    private MulticastSocket socketStu = null;
    // 使用常量作为本程序的多点广播目的的端口,DatagramSocket所用的的端口为该端口+1
    public static final int BROADCAST_PORT = 30000;
    // 定义广播的IP地址
    private InetAddress broadcastAddress = null;
    private InetAddress broadcastAddressStu = null;
    // 使用常量作为本程序的多点广播IP地址
    private static final String BROADCAST_IP = "224.2.2.2";
    private String hostName = null;//连接的wifi 对应的ip

    private EditText teachIp;
    // 定义每个数据报的最大大小为1K
    private static final int DATA_LEN = 1024 * 10;
    // 定义接收网络数据的字节数组
    byte[] inBuff = new byte[DATA_LEN];
    // 以指定字节数组创建准备接受数据的DatagramPacket对象
    private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
    private DatagramPacket inPacketStu = new DatagramPacket(inBuff, inBuff.length);
    // 定义一个用于发送的DatagramPacket对象
    private DatagramPacket outPacket = null;
    private DatagramPacket outPacketStu = null;

    private List<Msg> teachReciveMsgs, stuReciveMsgs;
    private MsgAdapter teacherMsgAdapter, stuMsgAdapter;
    private ListView tLv;

    private ImageView image;
    private Button startScreenBtn;

    private TextView ip_tv;

    private GridView onLineStuGv;
    private List<User> oneLineStus = new ArrayList<>();
    private OnlineStuAdapter onlineStuAdapter;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
//            if (image != null) {
            try {
                popDatagramPacket();
            } catch (Exception e) {
                e.printStackTrace();
            }
//            }
//            mHandler.postDelayed(this, 5000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flip_classroom);
        initView();
        getWifoIp();
        initOnClickListnner();
    }

    private void getWifoIp() {
        WifiManager wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();
        String ip = Formatter.formatIpAddress(ipAsInt);
        hostName = ip;
        ip_tv.setText(ip);
    }

    private void initOnClickListnner(){
        startScreenBtn.setOnClickListener(this);
    }

    public void initView() {
        tLv = findViewById(R.id.msg_teacher_lv);
        image = findViewById(R.id.show_im);
//        onLineStuGv = findViewById(R.id.am_gv);

        ip_tv = findViewById(R.id.ip_tv);

        teachIp = findViewById(R.id.teacher_ip_et);

        startScreenBtn = findViewById(R.id.start_screen);

        teachReciveMsgs = new ArrayList<>();
        stuReciveMsgs = new ArrayList<>();

        teacherMsgAdapter = new MsgAdapter(getApplicationContext(), teachReciveMsgs);
        stuMsgAdapter = new MsgAdapter(getApplicationContext(), stuReciveMsgs);
        tLv.setAdapter(teacherMsgAdapter);

//        onlineStuAdapter = new OnlineStuAdapter(getApplicationContext(), oneLineStus);
//        onLineStuGv.setAdapter(onlineStuAdapter);
    }


    //启动教师端
    public void startServer() throws IOException {
        Toast.makeText(this, "teacher", Toast.LENGTH_SHORT).show();
        socket = new MulticastSocket(BROADCAST_PORT);
        broadcastAddress = InetAddress.getByName(BROADCAST_IP);
        socket.joinGroup(broadcastAddress);// 将该socket加入指定的多点广播地址
        socket.setLoopbackMode(false);// 设置本MulticastSocket发送的数据报被回送到自身
        outPacket = new DatagramPacket(new byte[0], 0, broadcastAddress, BROADCAST_PORT); // 初始化发送用的DatagramSocket，它包含一个长度为0的字节数组

        // 启动两个读取网络数据的线程
        new ReadBroad().start();
    }

    //学生端初始化
    public void startServerStu(View view) throws IOException {
        Toast.makeText(this, "init stu MulticastSocket", Toast.LENGTH_SHORT).show();
        broadcastAddressStu = InetAddress.getByName(BROADCAST_IP);
        socketStu = new MulticastSocket(BROADCAST_PORT);
        socketStu.joinGroup(broadcastAddressStu);// 将该socket加入指定的多点广播地址
        socketStu.setLoopbackMode(false);// 设置本MulticastSocket发送的数据报被回送到自身
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] buffer = new byte[64 * 1024];
                Map<Long, HashMap<Integer, PackInfo>> map = null;
                final DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
                long key = 0;
                while (true) {
                    try {
                        socketStu.receive(pack);
//                        String data = new String(pack.getData());
//                        int i = data.indexOf("}");
//                        String u = data.substring(0, i + 1);
//                        Gson gson = new Gson();
//                        User user = gson.fromJson(u, User.class);

                        PackInfo packinfo = parsePackInfo(pack);
                        if (packinfo.getTime() > key) {
                            map = new HashMap<Long, HashMap<Integer, PackInfo>>();
                            HashMap<Integer, PackInfo> value = new HashMap<Integer, PackInfo>();
                            value.put(packinfo.getNum(), packinfo);
                            map.put(packinfo.getTime(), value);
                            // 更新key的值
                            key = packinfo.getTime();
                        } else if (packinfo.getTime() == key) {  //
                            map.get(key).put(packinfo.getNum(), packinfo);
                            // 检测是否够合成一张图片了，条件是map.value.size等于包的数量
                            checkMap(map);
                        }


//                        final String msg = new String(inBuff, 0, inPacketStu.getLength(), CHARSET);
//                        //System.out.println("学生端接收到的消息:" + msg);
//                        byte[] buffer = inPacketStu.getData();
//                        ByteArrayOutputStream b = new ByteArrayOutputStream();
//                        b.write(buffer);
//                        byte[] bytes = b.toByteArray();
//                        final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
////                        handleReciveData();
//
//                        //更新消息
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                image.setImageBitmap(bitmap);
//
//                                stuReciveMsgs.add(msg);
//                                stuMsgAdapter.notifyDataSetChanged();
//                                sLv.setSelection(stuMsgAdapter.getCount() - 1);
//                            }
//                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //获取教师发送来的屏幕数据
    public void getTeacherScreen() {
        Toast.makeText(this, "DatagramPacket start...", Toast.LENGTH_SHORT).show();
        DatagramSocket serScocket = null;
        InetSocketAddress addr = new InetSocketAddress(hostName, 8899);
        try {
            serScocket = new DatagramSocket(addr);//构造“邮局”
        } catch (SocketException e) {
            e.printStackTrace();
        }


        final DatagramSocket finalSerScocket = serScocket;
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] receive = new byte[64 * 1024];
                Map<Long, HashMap<Integer, PackInfo>> map = null;
                DatagramPacket dp = new DatagramPacket(receive, receive.length);//构建一个数据包；里面没有数据--相当于“空信封”（准备接收数据）
                long key = 0;
                while (true) {
                    try {
                        finalSerScocket.receive(dp);//接收数据，放到dp数据包，即把收到的数据封装到“空信封”里
                        PackInfo packinfo = parsePackInfo(dp);
                        if (packinfo.getTime() > key) {
                            map = new HashMap<Long, HashMap<Integer, PackInfo>>();
                            HashMap<Integer, PackInfo> value = new HashMap<Integer, PackInfo>();
                            value.put(packinfo.getNum(), packinfo);
                            map.put(packinfo.getTime(), value);
                            // 更新key的值
                            key = packinfo.getTime();
                        } else if (packinfo.getTime() == key) {  //
                            map.get(key).put(packinfo.getNum(), packinfo);
                            // 检测是否够合成一张图片了，条件是map.value.size等于包的数量
                            checkMap(map);
                            dp = new DatagramPacket(receive, receive.length);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //将个人连接信息发送给教师端
    public void sendMyHostToTeacher() throws SocketException {
        DatagramSocket serScocket = null;
        serScocket = new DatagramSocket();
        byte[] receive = new byte[1024];

        final DatagramSocket finalSerScocket = serScocket;
        new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] sendData = new byte[1024];

                String toC = "学生端发给服务端";
                InetAddress id = null;
                try {
                    id = InetAddress.getByName(teachIp.getText().toString());
                    sendData = toC.getBytes();
                    DatagramPacket dp1 = new DatagramPacket(sendData, sendData.length, id, 8898);//构造一封信DatagramPacket，信封里面封装了  待发数据、数据长、以及接收者信息
                    finalSerScocket.send(dp1);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 处理接收到屏幕图片数据
     * 用Map来存放屏幕图片的各个包数据，Long是接收到数据包的时间戳，Integer是包的编号
     * PackInfo中存放了解析出来的包数据、包数量、包编号、时间戳
     */
    private void handleReciveData() throws Exception {
        Map<Long, HashMap<Integer, PackInfo>> map = null;
        // key用于存放接收的上一个包数据的时间戳
        long key = 0;
//        while (true) {
        // 将收到的数据包解析成数据对象
        PackInfo packinfo = parsePackInfo(null);
        // 如果接收的的数据时间戳大于之前的包的时间戳，则丢弃之前的map，新建一个map，放入新的数据
        if (packinfo.getTime() > key) {
            map = new HashMap<Long, HashMap<Integer, PackInfo>>();
            HashMap<Integer, PackInfo> value = new HashMap<Integer, PackInfo>();
            value.put(packinfo.getNum(), packinfo);
            map.put(packinfo.getTime(), value);
            // 更新key的值
            key = packinfo.getTime();
        } else if (packinfo.getTime() == key) {
            map.get(key).put(packinfo.getNum(), packinfo);
            // 检测是否够合成一张图片了，条件是map.value.size等于包的数量
            checkMap(map);
        }
//        }
    }

    // 检测放入的小包是否等于包的总数，等于则合成一张图片
    public void checkMap(Map<Long, HashMap<Integer, PackInfo>> map) throws Exception {
        Iterator<Map.Entry<Long, HashMap<Integer, PackInfo>>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Long, HashMap<Integer, PackInfo>> entry = it.next();
            PackInfo packinfo = entry.getValue().entrySet().iterator().next().getValue();
            System.out.println("key:" + packinfo.getTime() + "包总量：" + packinfo.getCount() + "，map的值总量：" + entry.getValue().size());
            // 检测是否集齐了所有小包，集齐了就合成一帧图片
            if (packinfo.getCount() == entry.getValue().size()) {
                // //System.out.println("满了，合成图片");
                // 将各个小包合成图片
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                for (int i = 0; i < packinfo.getCount(); i++) {
                    PackInfo p = entry.getValue().get(i);
                    baos.write(p.getData());
                }
                baos.close();
                // 解压缩数据
//                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
//                ZipInputStream zis = new ZipInputStream(bais);
//
//
//                zis.getNextEntry();

                final byte[] bytes = baos.toByteArray();
                //System.out.println("接收到的数据大小：" + bytes.length);
//                updateTeacherMsgList("接收到的数据大小：" + bytes.length);
                final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//                image.setImageBitmap(bitmap);
                final BitmapDrawable drawable = new BitmapDrawable(image.getResources(), bitmap);
//
//
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        RequestOptions options = new RequestOptions()
                                .circleCrop()                        // 设置图片变换为圆角
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .placeholder(R.mipmap.ic_launcher)   // 设置站位图
                                .error(R.mipmap.ic_launcher_round);  // 设置加载失败的错误图片

                        Glide.with(getApplicationContext())
                                .load("https://${System.currentTimeMillis()}")//随便给个不可用的url
                                .into(image);
                    }
                });

                it.remove();
            }
        }
        //  //System.out.println("字典长度 = " + map.size());
    }

    private PackInfo parsePackInfo(DatagramPacket pack) {
        // 新建一个包数据对象存放数据
        PackInfo packinfo = new PackInfo();

        byte[] buffer = pack.getData();

        // 取出时间戳，0-7的字节
        long time = Util.byte2Long(buffer, 0);
        packinfo.setTime(time);

        // 取出分割数量，8-11的字节
        int count = Util.byte2Int(buffer, 8);
        packinfo.setCount(count);

        // 取出当前编号，12-15的字节
        int num = Util.byte2Int(buffer, 12);
        packinfo.setNum(num);

        // 当前被压缩后的数据
        byte[] data = new byte[pack.getLength() - 16];
        System.arraycopy(buffer, 16, data, 0, data.length);
        packinfo.setData(data);
        return packinfo;
    }

    //学生端发送消息到服务端
    public void broadCastScreenStu(View view) {
        String msg = "学生：";
        try {
            byte[] buff = msg.getBytes(CHARSET);// 将msg字符串转换字节数组
            outPacketStu.setData(buff);// 设置发送用的DatagramPacket里的字节数据
            socketStu.send(outPacketStu);// 发送数据报
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start_screen:
                String tip = teachIp.getText().toString();
                if (teachIp.getText().toString().equals("")){
                    Toast.makeText(getApplicationContext(),"请填入教师端IP",Toast.LENGTH_SHORT).show();
                    return;
                }
                getTeacherScreen();
                try {
                    sendMyHostToTeacher();
                } catch (SocketException e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    // 持续读取MulticastSocket的线程
    class ReadBroad extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    socket.receive(inPacket);
//                    final String msg = new String(inBuff, 0, inPacket.getLength(), CHARSET);
                    //更新消息
                    updateTeacherMsgList(System.currentTimeMillis() + ":收到新消息");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //更新消息列表
    private void updateTeacherMsgList(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int[] ids = new int[]{R.mipmap.avatar_boy, R.mipmap.avatar_girl, R.mipmap.avatar_man_teacher, R.mipmap.avatar_woman_teacher};
                int i = (int) (Math.random() * 3);
                Msg m = new Msg();
                m.setMessage(msg);
                m.setAvatar(ids[i]);

                if (teachReciveMsgs.size() > 5000) {
                    teachReciveMsgs.remove(0);
                }
                teachReciveMsgs.add(m);
                teacherMsgAdapter.notifyDataSetChanged();
                tLv.setSelection(teacherMsgAdapter.getCount() - 1);
            }
        });
    }

    ///广播屏幕
    public void broadCastScreen(final View view) throws IOException {
        startScreenBtn.setEnabled(false);
        startScreenBtn.setText("广播中...");
        startServer();
//        startServerStu();

        //测试在线学生数据
        int[] ids = new int[]{R.mipmap.avatar_boy, R.mipmap.avatar_girl};
        for (int i = 0; i < 54; i++) {
            User u = new User();
            u.setName("学生" + i);
            u.setAvatar(i / 4 == 0 ? ids[1] : ids[0]);
            oneLineStus.add(u);
        }
        onlineStuAdapter.notifyDataSetChanged();

        try {
            popDatagramPacket();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //bitmap转byte[]
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
//        byte[] bytes = baos.toByteArray();
//        outPacket = new DatagramPacket(bytes, bytes.length, broadcastAddress, BROADCAST_PORT);// 设置发送用的DatagramPacket里的字节数据
//        try {
//            socket.send(outPacket);// 发送数据报
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        //分割字节并发送
//        cutBytesAndPost(bytes);


        //获取屏幕图片、压缩、分割发送

//        String msg = "教师：" + tEt.getText();
//        try {
//            byte[] buff = msg.getBytes(CHARSET);// 将msg字符串转换字节数组
//            outPacket.setData(buff);// 设置发送用的DatagramPacket里的字节数据
//            socket.send(outPacket);// 发送数据报
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }


    private void popDatagramPacket() throws Exception {
        Long startTimeMillis = System.currentTimeMillis();
        //构建Bitmap
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int w = metrics.widthPixels;
        int h = metrics.heightPixels;
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

        //获取屏幕
        View decorview = getWindow().getDecorView();
        Canvas canvas = new Canvas(bmp);
        decorview.draw(canvas);

//        myBmp = bmp;
        Long endTimeMillis = System.currentTimeMillis() - startTimeMillis;
        //System.out.println("获取屏幕时长：" + endTimeMillis + "ms");
        //bitmap转byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        // 过压缩
//        byte[] buffer = compressImage(bytes);
        // 分割图片并发送出去
        cutImageByteAndPost(bytes);
        updateTeacherMsgList("发送的数据大小：" + bytes.length);
        mHandler.postDelayed(myRunnable, 0);
//        image.setImageBitmap(bmp);
    }

    // 将数据的byte[]分割发送出去，同一帧的图片分割成的小包，有着相同的时间戳，同样的包数量，不同的编号
    // 每一个小包，开始8个字节存放时间戳，接下来四个字节存放本帧图片所分割出来的包数量，再放入四个字节的编号
    public void cutImageByteAndPost(byte[] src) {
        InetAddress group;
        MulticastSocket multicastSocket = null;//
        try {

            int len = src.length;
            // 分割的包数量
            int count = len / 60 / 1024;
            if (len > count * 60 * 1024) {//
                count++;
            }
            byte[] buffer = new byte[60 * 1024 + 8 + 4 + 4];
            long time = System.nanoTime();
            // 发count数量的包
            for (int i = 0; i < count; i++) {
                Long startTimeMillis = System.currentTimeMillis();
                // 如果是最后一个包，就将剩下的所有数据都发送出去
                if (i == count - 1) {//
                    buffer = new byte[len % (60 * 1024) + 16];
                }
                // 写入时间戳
                System.arraycopy(Util.long2Byte(time), 0, buffer, 0, 8);
                // 写入分割的数量
                System.arraycopy(Util.int2Byte(count), 0, buffer, 8, 4);
                // 写入当前的编号，从0开始
                System.arraycopy(Util.int2Byte(i), 0, buffer, 12, 4);
                // 写入image内容
                System.arraycopy(src, i * 60 * 1024, buffer, 16, buffer.length - 16);

                Long endTimeMillis = System.currentTimeMillis() - startTimeMillis;
                // 发送数据，组装成数据报包
                Long startTimeMillis1 = System.currentTimeMillis();
                // 设置发送地址、端口
                multicastSocket = new MulticastSocket(BROADCAST_PORT);
                group = InetAddress.getByName(BROADCAST_IP);
                multicastSocket.joinGroup(group);
                DatagramPacket pack = new DatagramPacket(buffer, buffer.length, group, BROADCAST_PORT);
                multicastSocket.send(pack);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 将image的byte[]过压缩，返回压缩后的byte[]
    private byte[] compressImage(byte[] buffer) throws Exception {
        // 新建一个baos，用于存放转压缩后的byte[]数据
        Long startTimeMillis = System.currentTimeMillis();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        ZipEntry entry = new ZipEntry("image.jpg");
        zos.setLevel(5);
        // 放入条目
        zos.putNextEntry(entry);
        // 写入数据
        zos.write(buffer);

        zos.close();
        baos.close();
        Long endTimeMillis = System.currentTimeMillis() - startTimeMillis;
        //System.out.println("(压缩) 结束，用时:" + endTimeMillis + " ms");
        return baos.toByteArray();
    }

    /**
     * @param src
     * @des 将数据的byte[]分割发送出去，同一帧的图片分割成的小包，有着相同的时间戳，同样的包数量，不同的编号
     * 每一个小包，开始8个字节存放时间戳，接下来四个字节存放本帧图片所分割出来的包数量，再放入四个字节的编号
     */
    private void cutBytesAndPost(byte[] src) {

        int len = src.length;
        //分割的包数量
        int count = len / 60 / 1024;
        if (len > count * 60 * 1024) {
            count++;
        }
        byte[] buffer = new byte[60 * 1024 + 8 + 4 + 4];
        long time = System.nanoTime();

        //发count数量的包
        for (int i = 0; i < count; i++) {
            //如果是最后一个包，就将剩下的所有数据都发送出去
            if (i == count - 1) {
                buffer = new byte[len % (60 * 1024) + 16];
            }
            //  * 写入时间戳
            System.arraycopy(Util.long2Byte(time), 0, buffer, 0, 8);
            //  * 写入分割的数量
            System.arraycopy(Util.int2Byte(count), 0, buffer, 8, 4);
            // * 写入当前的编号，从0开始
            System.arraycopy(Util.int2Byte(i), 0, buffer, 12, 4);
            // * 写入image内容
            System.arraycopy(src, i * 60 * 1024, buffer, 16, buffer.length - 16);

            outPacket = new DatagramPacket(buffer, buffer.length, broadcastAddress, BROADCAST_PORT);// 设置发送用的DatagramPacket里的字节数据
            try {
                socket.send(outPacket);// 发送数据报
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }



}